package com.test.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtil {
    // 静态SqlSessionFactory（全局唯一，初始化一次）
    private static SqlSessionFactory sqlSessionFactory;

    // 静态代码块：加载mybatis-config.xml，初始化SqlSessionFactory
    static {
        try {
            // 1. 读取MyBatis核心配置文件
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);

            // 2. 构建SqlSessionFactory
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            throw new RuntimeException("MyBatis初始化失败！", e);
        }
    }

    // 获取SqlSession（true=自动提交事务，false=手动提交）
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession(true);
    }
}
